<style lang="scss" scoped="">
  @import "../utils/base.scss";
</style>
<template>
  <div>
    <pheader>
      <template slot="left">用户管理/公告发送</template>
    </pheader>
    <div style="padding: 8px 8px 0px 8px;">
      <div
        style="width: 100%;background-color: white;height: calc(100vh - 108px);overflow-y: auto;overflow-x:hidden;padding:40px;">
        <Form :model="baseInfo" label-position="left" :label-width="110" style="position:relative;left:4%">
          <Row>
            <Col>
            <FormItem label="公告标题：" :required="true">
              <Input v-model="baseInfo.title" style="width:90%" />
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="24">
            <FormItem label="公告内容：" :required="true">
              <!-- <Input v-model="baseInfo.des" type="textarea" maxlength="250" show-word-limit :rows="3" style="width:90%" /> -->
              <mavon-editor ref="md" :toolbars='toolbars' :xssOptions="xssList" v-model='baseInfo.des'
                style="height: 400px;z-index:100;width:91%;" @imgAdd="imgAdd" @imgDel="imgDel"></mavon-editor>
            </FormItem>
            </Col>
          </Row>
          <!-- <Row style="padding-bottom:2%">
            <Col span="24">
            <mavon-editor ref="md" :toolbars='toolbars' :xssOptions="xssList" v-model='baseInfo.des'
              style="height: 400px;z-index:100;width:91%;" @imgAdd="imgAdd" @imgDel="imgDel"></mavon-editor>
            </Col>
          </Row> -->
          <Row>
            <Col>
            <FormItem label="通知的租户：">
              <template v-for="(item,index) in tenants">
                <CheckboxGroup v-model="noticeTenantList" @on-change="selectTenant">
                  <Row>
                    <Col>
                    <Checkbox :label="item" :disabled="(noticeTenantList.indexOf('所有租户')>-1) && (item != '所有租户')">
                    </Checkbox>
                    </Col>
                  </Row>
                </CheckboxGroup>
                <CheckboxGroup v-model="selectTypeList" @on-change="selectTenantType"
                  v-if="(noticeTenantList.indexOf('租户类型')>-1) && (item === '租户类型')">
                  <Row>
                    <Col style="left:2%">
                    <Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="handleCheckAll">全选
                    </Checkbox>
                    </Col>
                  </Row>
                  <Row>
                    <template v-for="(item,index) in tenantType">
                      <Col span="6" style="left:2%">
                      <Checkbox :label="item.projectType"></Checkbox>
                      </Col>
                    </template>
                  </Row>
                </CheckboxGroup>
                <div style="position: relative;left:2%"
                  v-if="(noticeTenantList.indexOf('指定租户')>-1) && (item === '指定租户')">
                  <Tag v-if="tenantInfoList.length > 0" v-for="(tenant,i) in tenantInfoList" :key="i" :name="tenant.id"
                    closable @on-close="delTenant(i)">{{tenant.tenant_name}}</Tag>
                  <Button type="primary" size="small" @click="setTenant()">
                    <Icon type="ios-add" style="line-height: 8px;padding-right:8px;" />添加租户
                  </Button>
                </div>
              </template>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col>
            <FormItem label="通知的用户：">
              <template v-for="(item,index) in people">
                <CheckboxGroup v-model="noticePeopleList" @on-change="selectPeople">
                  <Row>
                    <Col>
                    <Checkbox :label="item" :disabled="(noticePeopleList.indexOf('所有用户')>-1) && (item != '所有用户')">
                    </Checkbox>
                    </Col>
                  </Row>
                </CheckboxGroup>
                <div style="position: relative;left:2%"
                  v-if="(noticePeopleList.indexOf('指定用户')>-1) && (item === '指定用户')">
                  <Tag v-if="peopleInfoList.length > 0" v-for="(user,i) in peopleInfoList" :key="i" :name="user.id"
                    closable @on-close="delUser(i)">{{user.user_name}}</Tag>
                  <Button type="primary" size="small" @click="setUser()">
                    <Icon type="ios-add" style="line-height: 8px;padding-right:8px;" />添加用户
                  </Button>
                </div>
              </template>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col>
            <FormItem label="是否短信通知：">
              <Checkbox v-model="baseInfo.ifSMS"></Checkbox>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col style="padding-bottom: 10px;left:83%">
            <Button type="primary" @click="send()">确定发送</Button>
            </Col>
          </Row>
        </Form>
      </div>
    </div>
    <Modal v-model="ifSelectTenant" title="选择指定租户" width="680" @on-ok="ok_tenant" @on-cancel="cancel_tenant">
      <component v-if="ifSelectTenant" ref="transferTenant"  :is="'transferTenant'" :title="title"
        v-model="tenantInfoList"></component>
    </Modal>
    <Modal v-model="ifSelectPeople" title="选择指定用户" width="680" @on-ok="ok_people" @on-cancel="cancel_people">
      <component v-if="ifSelectPeople" ref="transfer"  :is="'transfer'" :title="title" :existence="'已选择该用户'"
        v-model="peopleInfoList"></component>
    </Modal>
  </div>
</template>

<script>
  import pheader from "../comp_chatter/pheader"
  import Axios from 'axios'
  import ajax from "../ajax_util"
  import transfer from '../base/transfer'
  import transferTenant from '../base/transfer_tenant'
  var mavonEditor = require('mavon-editor')
  import 'mavon-editor/dist/css/index.css'
  var xss = require('xss')
  var md_img_g = {}

  export default {
    components: {
      pheader,
      transfer,
      transferTenant,
      'mavon-editor': mavonEditor.mavonEditor
    },
    data() {
      return {
        xssList: {
          whiteList: xss.whiteList
        },
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          superscript: true, // 上角标
          subscript: true, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: false, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: true, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
        },
        mdvalue: '',

        title: ["未选择", "已选择"],

        baseInfo: {
          msgId: 0,
          title: "",
          des: "",
          tenantType: [],
          tenantList: [],
          userList: [],
          ifSMS: false
        },

        tenants: ["所有租户", "租户类型", "指定租户"],
        people: ["所有用户", "指定用户"],

        noticeTenantList: [],
        noticePeopleList: [],

        tenantType: [],
        selectTypeList: [],

        tenantInfoList: [],
        peopleInfoList: [],

        indeterminate: false,
        checkAll: false,

        ifSelectTenant: false,
        ifSelectPeople: false
      }
    },

    mounted() {
      this.getTenantType();
    },
    methods: {
      imgAdd(filename, imgfile) {
        let img_name = guid(this.$store.state.user.id);
        this.$refs.md.$img2Url(filename, img_name); //md中图片改名
        this.$refs.md.$imgUpdateByUrl(img_name, imgfile.miniurl); //md中图片改名后会对应不上图片文件，这里是把图片文件重新给对应图片
        md_img_g[img_name] = imgfile; //记录图片，后面上传用
      },
      imgDel(filename) {
        console.log('------------imgDel------------', filename)
      },
      selectTenant(data) {
        console.log("=====111=======");
        if (data.indexOf('所有租户') > -1) {
          this.noticeTenantList = ["所有租户"];
        }

        if (this.noticeTenantList.indexOf('租户类型') < 0) {
          console.log("77777777");
          this.selectTypeList = [];
          this.indeterminate = false;
          this.checkAll = false;
        }

        if (this.noticeTenantList.indexOf('指定租户') < 0) {
          this.tenantInfoList = [];
        }

        console.log(this.noticeTenantList);
        console.log(data);
        console.log("===999==", this.indeterminate);
      },
      selectPeople(data) {
        if (data.indexOf('所有用户') > -1) {
          this.noticePeopleList = ["所有用户"];
        }

        if (this.noticePeopleList.indexOf('指定用户') < 0) {
          this.peopleInfoList = [];
        }
      },
      handleCheckAll() {
        if (this.indeterminate) {
          this.checkAll = false;
        } else {
          this.checkAll = !this.checkAll;
        }
        this.indeterminate = false;

        if (this.checkAll) {
          console.log("===全选==");
          for (var i = 0; i < this.tenantType.length; i++) {
            this.selectTypeList.push(this.tenantType[i].projectType);
          }
          console.log("===全选==", this.selectTypeList);
        } else {
          this.selectTypeList = [];
        }
      },
      selectTenantType(data) {
        console.log("=====222=======");
        console.log(this.selectTypeList);
        console.log(data);
        var len = this.tenantType.length;
        if (data.length === len) {
          this.indeterminate = false;
          this.checkAll = true;
        } else if (data.length > 0) {
          this.indeterminate = true;
          this.checkAll = false;
        } else {
          this.indeterminate = false;
          this.checkAll = false;
        }
      },
      setTenant() {
        this.ifSelectTenant = true;
      },
      setUser() {
        this.ifSelectPeople = true;
      },
      delTenant(index) {
        this.tenantInfoList.splice(index, 1);
      },
      delUser(index) {
        this.peopleInfoList.splice(index, 1);
      },
      ok_tenant() {},
      cancel_tenant() {},
      ok_people() {},
      cancel_people() {},
      getTenantType() {
        var that = this;
        var url = this.CONFIG.url_know + '/getTenantType';
        ajax.get({
          url: url,
          that: that,
          success: function(data) {
            that.tenantType = data;
          }
        });
      },
      send() {
        var selectType = [];
        var tenantList = [];
        if (this.noticeTenantList.indexOf('所有租户') > -1) {
          selectType.push("所有租户");
        } else {
          for (var i = 0; i < this.tenantInfoList.length; i++) {
            tenantList.push(this.tenantInfoList[i].id);
          }
        }

        var userList = [];
        if (this.noticePeopleList.indexOf('所有用户') > -1) {
          selectType.push("所有用户");
        } else {
          for (var i = 0; i < this.peopleInfoList.length; i++) {
            userList.push(this.peopleInfoList[i].id);
          }
        }

        this.baseInfo.tenantType = this.selectTypeList.concat(selectType);
        this.baseInfo.tenantList = tenantList;
        this.baseInfo.userList = userList;
        if (this.baseInfo.title == "" || this.baseInfo.title == null || this.baseInfo.title == undefined) {
          this.$Message.warning({
            content: '请填写公告标题!'
          });
        } else if (this.baseInfo.des == "" || this.baseInfo.des == null || this.baseInfo.des == undefined) {
          this.$Message.warning({
            content: '请填写公告内容!'
          });
        } else if (this.baseInfo.tenantType.length == 0 && this.baseInfo.tenantList.length == 0 && this.baseInfo
          .userList == 0) {
          this.$Message.warning({
            content: '请选择通知对象!'
          });
        } else {
          var formdata = new FormData();
          var img_arr = []
          var matched_arr = this.baseInfo.des.match(/\!\[.*?]\((.*?)\)/g);
          console.log("v", md_img_g, this.baseInfo.des)
          for (var i in matched_arr) {
            console.log("for")
            var img_name = /\!\[.*?]\((.*?)\)/g.exec(matched_arr[i])[1];
            img_arr.push({
              name: img_name
            })
            formdata.append(img_name, md_img_g[img_name])
          }
          this.$Modal.confirm({
            title: '确定发送公告？',
            width: '360',
            onOk: () => {
              var img_url = this.CONFIG.file_url + '/named-images'
              console.log('img_url', img_url)
              console.log('formdata', formdata)
              Axios({
                url: img_url,
                method: 'post',
                data: formdata,
                headers: {
                  'Content-Type': 'multipart/form-data'
                },
              }).then(response => {
                console.log("------this.baseInfo-------");
                console.log(this.baseInfo);
                let m = {
                  startId: this.$store.state.user.id,
                  startName: this.$store.state.user.user_name,
                  msg: this.baseInfo
                };
                console.log(m);
                var that = this;
                var url = this.CONFIG.msg_url + '/notice';
                ajax.post({
                  url: url,
                  that: that,
                  data: m,
                  success: function(data) {
                    console.log(data);
                    if (data == 1) {
                      that.$Message.success({
                        content: '发送成功!'
                      });
                    } else {
                      that.$Message.error({
                        content: '发送失败,请联系相关人员!'
                      });
                    }
                  }
                });
              })
            }
          });

          // console.log("------this.baseInfo-------");
          // console.log(this.baseInfo);
          // this.$Modal.confirm({
          //     title:'确定发送公告？',
          //     width:'360',
          //     onOk:() => {
          //         let m={
          //             startId:this.$store.state.user.id,
          //             startName:this.$store.state.user.user_name,
          //             msg:this.baseInfo
          //         };
          //         console.log(m);
          //         var that = this;
          //         var url = this.CONFIG.msg_url+'/notice';
          //         ajax.post({
          //           url:url,
          //           that:that,
          //           data:m,
          //           success:function(data){
          //             console.log(data);
          //             if(data == 1){
          //                 that.$Message.success({
          //                     content: '发送成功!'
          //                 });
          //             }else{
          //                 that.$Message.error({
          //                     content: '发送失败,请联系相关人员!'
          //                 });
          //             }
          //         }});
          //     }
          // });
        }
      }
    }
  }

  function guid(userId) {
    var time = new Date().getTime()
    var use = '' + userId
    var user = use
    for (let i = 0; i < 5 - use.length; i++) {
      user += '0'
    }
    var temp = parseInt(time + '' + user).toString(32) + '' + parseInt(Math.random() * 100000)
    console.log(time, user, parseInt(time + '' + user), temp)

    return temp;
  }
</script>
